<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->

    <el-card>
      <!-- 添加角色列表按钮区域 -->
      <el-row :gutter="40">
        <!-- <el-col :span="8">
            <el-input el-input placeholder="请输入需要查询的角色ID" v-model="queryInfo.roleId" clearable @clear="getRolesList">
            <el-button slot="append" icon="el-icon-search" @click="getRolesList"></el-button>
          </el-input>
        </el-col> -->
        <el-col :span="6">
          <el-button type="primary" @click="addCharacter = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleslist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" size="mini">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级标题 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)"> {{ item1.authName }} </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级标题 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染二级标题 -->
                <el-row :class="[i2 === 0 ? '' : 'bdttop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3,) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{ scope.row }}
            </pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="290px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="renoveUserById(scope.row.id)">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-s-tools" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加用户" :visible.sync="addCharacter" width="50%" @close="CharacterReset">
      <!-- 内容主体区域 -->
      <el-form :model="CharacterFrom" :rules="CharacterFromRules" ref="CharacterFromRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
           <el-input v-model="CharacterFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
           <el-input v-model="CharacterFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCharacter = false">取 消</el-button>
        <el-button type="primary" @click="addCharacterUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
     <!-- 修改用户的对话框 -->
     <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="60%" @close="editDialogClosed">
      <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="90px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserInfo">确定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="60%" @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree :data="rightlist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="allotRights">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        roleId: ''
      },
      roleslist:[],
      // 显示与隐藏添加用户的对话框
      addCharacter: false,
      // 添加角色的表单数据
      CharacterFrom: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      // 添加角色的表单验证规则对象
      CharacterFromRules: {
        roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 3, max: 10, message: '用户名长度在3~10个字符之间', trigger: 'blur' }
        ],
        roleDesc: [
        { required: true, message: '请输入角色描述', trigger: 'blur' },
        { min: 3, max: 10, message: '用户名长度在3~10个字符之间', trigger: 'blur' }
        ]
      },
      // 查询到角色私有信息对象
      editFrom: {},
      // 修改表单验证规则对象
      editFromRules: {
        roleDesc: [
        { required: true, message: '请输入角色描述', trigger: 'blur' },
        { min: 3, max: 10, message: '用户名长度在3~10个字符之间', trigger: 'blur' }
        ]
      },
      // 修改对话框的显示与隐藏
      editDialogVisible: false,
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightlist: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKeys:[
        
      ],
      // 即将分配权限的角色ID
      roleId:''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const {data: res} = await this.$http.get('roles', {params: this.queryInfo})
      if(res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleslist = res.data
      console.log(this.roleslist);
    },
    // 失去焦点重置添加用户对话框
    async CharacterReset() {
      await this.$refs.CharacterFromRef.resetFields()
    },
    // 点击确定添加角色
    addCharacterUser() {
      this.$refs.CharacterFromRef.validate(async valid => {
        // 校验是否通过
        if(!valid) return
        // 校验通过发起添加角色网络请求
        const { data:res } = await this.$http.post ('roles',this.CharacterFrom)
        if(res.meta.status !== 200) {
          this.$message.error('添加角色失败！')
        }
        // 添加角色成功操作
        this.$message.success('添加角色成功')
        // 添加成功之后隐藏用户对话框
        this.addCharacter = false
        // 重新获取角色列表
        this.getRolesList()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      console.log(id);
      const {data : res} = await this.$http.get('roles/' + id)
      if( res.meta.status !== 200) return this.$message.error('修改角色失败！')
      this.editFrom = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    async editDialogClosed() {
      await this.$refs.editFromRef.resetFields()
    },
    // 修改角色信息并提交
    editUserInfo() {
      this.$refs.editFromRef.validate( async valid => {
        // console.log(valid);
        if(!valid) return this.$message.error('编辑角色描述失败！')
        // 校验通过表示可以发起修改用户网络请求
        const {data : res} = await this.$http.put('roles/' + this.editFrom.roleId, {
          roleName: this.editFrom.roleName,
          roleDesc: this.editFrom.roleDesc,
        })
        // console.log(res);
        if(res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }
        
        // 修改成功之后隐藏修改用户对话框
        this.editDialogVisible = false
        // 重新获取用户列表
        this.getRolesList()
        // 提示用户信息修改成功
        this.$message.success('修改角色描述成功')
      })
    },
    // 删除角色

      // 根据id删除对应用户
    async renoveUserById(id) {
      console.log(id);
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 如果用户确认删除，则返回值为confirm
        // 如果用户取消了删除，则返回值我字符串 cancel
        // console.log(confirmResult);
        if(confirmResult !== 'confirm') {
          return this.$message.info('用户取消了删除')
        }
      // console.log('确认删除');
      const {data : res} = await this.$http.delete('roles/' + id)

      if(res.meta.status !== 200) {
        return this.$message.error('删除用户是失败')
      }
      this.$message.success('删除用户成功')
      // 删除成功后重新获取用户列表
      this.getRolesList()
      },
      // 根据ID删除对应权限
      async removeRightById(role, rightId) {
        const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 如果用户确认删除，则返回值为confirm
        // 如果用户取消了删除，则返回值我字符串 cancel
        console.log(confirmResult);
        if(confirmResult !== 'confirm') {
          return this.$message.info('用户取消了删除')
        }
        // 确认删除
        const {data : res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)

        if(res.meta.status !== 200) {
          return this.$message.error('删除权限是失败')
        }
        this.$message.success('删除用户成功')
        // 删除成功后重新获取用户列表
        // this.getRolesList()
        role.children = res.data
      },
      // 这是展示分配权限对话框
      async showSetRightDialog(role) {
        this.roleId = role.id
        const { data : res } = await this.$http.get('rights/tree')
        this.setRightDialogVisible = true
        if(res.meta.status !== 200) {
          return this.$message.error('获取权限数据失败！')
        }
        // 获取到的权限数据
        this.rightlist = res.data
        console.log(this.rightlist);
        // 递归获取到的三级节点
        this.getLeafKeys(role,this.defKeys)
        this.setRightDialogVisible = true
      },
      // 通过递归的形式，获取角色所有的三级权限的id，并保存到defKeys中
      getLeafKeys(node,arr) {
        // 如果当前 node 节点不包含children属性，则是三级节点
        if (!node.children) {
          return arr.push(node.id)
        }

        node.children.forEach(item => this.getLeafKeys(item, arr))
      },
      setRightDialogClosed() {
        this.defKeys = []
      },
      // 点击确定分配权限
      async allotRights() {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        console.log(keys);

        const idStr = keys.join(',')
        const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{
          rids: idStr
        })

        if(res.meta.status !== 200) {
          return this.$message.error('分配权限失败！')
        }
        this.$message.success('分配权限成功')
        this.getRolesList()
        this.setRightDialogVisible = false
      }
    }
  }

</script>

<style lang="less" scoped>
  .el-tag{
    margin: 8px 0px 8px 20px;
  }

  .bdttop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
    
  }

  // .el-button{
  //   position:sticky !important;
  // }
</style>